package com.coovane.bytetrix.service.impl.system;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coovane.bytetrix.common.enumeration.ErrorCodeEnum;
import com.coovane.bytetrix.common.exception.GenericAssert;
import com.coovane.bytetrix.common.exception.GenericException;
import com.coovane.bytetrix.common.model.system.AdminLoginLogDTO;
import com.coovane.bytetrix.common.model.system.AdminLoginLogListVO;
import com.coovane.bytetrix.common.model.system.AdminLoginLogQuery;
import com.coovane.bytetrix.common.util.ConvertUtils;
import com.coovane.bytetrix.common.util.Copier;
import com.coovane.bytetrix.dao.system.AdminLoginLogDao;
import com.coovane.bytetrix.domain.system.AdminLoginLog;
import com.coovane.bytetrix.service.system.AdminLoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 管理员用户登录日志service实现
 * </p>
 *
 * @author: Hsu
 * @date: 2022/12/2 20:18
 * @copyright: companyName
 * @see
 * @since 1.8
 */
@Slf4j
@Service
public class AdminLoginLogServiceImpl extends ServiceImpl<AdminLoginLogDao, AdminLoginLog> implements AdminLoginLogService {

    /**
     * 分页查询
     *
     * @param query
     * @return
     */
    @Override
    public IPage<AdminLoginLogListVO> pageQuery(AdminLoginLogQuery query) {
        Page<AdminLoginLog> page = new Page<>(query.getPage(), query.getLimit());
        LambdaQueryWrapper<AdminLoginLog> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(query.getUserId())) {
            queryWrapper.eq(AdminLoginLog::getUserId, query.getUserId());
        }
        if (StringUtils.isNotBlank(query.getUsername())) {
            queryWrapper.like(AdminLoginLog::getUsername, query.getUsername());
        }
        Page<AdminLoginLog> loginLogPage = this.getBaseMapper().selectPage(page, queryWrapper);
        return loginLogPage.convert(loginLog -> ConvertUtils.convert(loginLog, AdminLoginLogListVO.class));
    }

    /**
     * 新增
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(AdminLoginLogDTO dto) {
        log.info("=====create adminLoginLogDTO:{}", JSONObject.toJSONString(dto));
        AdminLoginLog loginLog = Copier.copy(dto, new AdminLoginLog());
        boolean saveResult = this.save(loginLog);
        GenericAssert.isTrue(saveResult, new GenericException(ErrorCodeEnum.OPERATE_FAILED));
        log.info("=====create loginLog:{}", JSONObject.toJSONString(loginLog));
        return loginLog.getId();
    }

}
